# -*-coding: utf-8 -*-
"""
    @Theme   : 登录与授权
    @Time    : 2024/4/10 12:50
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import current_user, login_user, logout_user, login_required

from suzyblog.forms import LoginForm
from suzyblog.utils import redirect_back
from suzyblog.models import Admin

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('blog.index'))
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        remember = form.remember.data
        admin = Admin.query.first()
        if admin:
            if username == admin.username and admin.validate_password(password):
                login_user(admin, remember)
                flash('Login Success!', 'info')
                return redirect_back()
            flash('Invalid username or password!', 'warning')
        else:
            flash('No admin Account', 'warning')
    return render_template('auth/login.html', form=form)


@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('Logout Success!', 'info')
    return redirect_back()

